<?php

// Include shared script

require_once('shared.php');


// ---------- DATABASE STATEMENTS ----------

// Imported data

$stmtImport1 = $db->query(
	'SELECT			*
	FROM			sherpa_importData
	ORDER BY		id ASC'
);


// ---------- VALIDATION ----------

// Flag to indicate whether validation succeeded or not
$success = true;


// Walk through all import records
$lastArticleNumber = null;
$parentMissing = false;
$parentId = null;
$countChildren = null;

while ($importData = $stmtImport1->fetch(PDO::FETCH_ASSOC)) {

	// If article number changed, this must be a parent product
	if ($importData['articleNumber'] != $lastArticleNumber) {
		
		// Check whether parent has no children
		if ($countChildren !== null && $countChildren == 0) {
			echo 'Children fehlen fuer Artikelnummer ' . $lastArticleNumber . '<br />';
			$success = false;
		}
		else {
			$countChildren = 0;
		}
		
		$lastArticleNumber = $importData['articleNumber'];
		$parent = true;
		$parentMissing = false;
		$parentId = null;
	}
	else {
		$parent = false;
		$countChildren++;
	}

	// Make sure parent has no EAN code, otherwise it must be a child that's missing a parent
	if ($parent && $importData['eanCode'] != null) {
		$parentMissing = true;
	}

	// Error if parent is missing
	if ($parentMissing) {
		echo 'Parent fehlt fuer Artikelnummer ' . $importData['articleNumber'] . '<br />';
		$success = false;
	}
	
}

// Check whether parent has no children for last import record
if ($countChildren == 0) {
	echo 'Children fehlen fuer Artikelnummer ' . $lastArticleNumber . '<br />';
		$success = false;
}


if ($success) {
	echo 'Import-Daten erfolgreich ueberprueft.';
}
else {
	echo 'Import-Daten sind fehlerhaft.';
}

